

--[[
	Usage:
	local a = g.callcc(function(cc)  
		print(1)
		cc(2);
		print(2)
		return 1;
	end)

	warn(a);
	
	--- 注意: 这里的cc是current continuation, 也就是"当前执行点出的后续"	
]]
local function callcc(f)
	local co = coroutine.create(f)
	local ok, val = coroutine.resume(co, function(...)
		return coroutine.yield(...)
	end)
	if ok then
		return val
	else
		error(val)
	end
end

return callcc;

--[[
Examples:
	local a = g.callcc(function(cc)
		print(1)
		cc(2);
		print(2)
		return 1;
	end)


	function ForEach(array, handler)
		g.callcc(function(breaker) 
			for i, v in ipairs(array) do
				handler(i, v, breaker)
			end
		end)
	end

	local arr = {1, 2, 3, 4, 5, 6, 7};
	ForEach(arr, function(i, v, breaker)
		if i > 5 then
			breaker();
		end
		warn(v);
	end);

	function whiler(cond, body)
		return g.callcc(function(breaker)
			if cond() then
				body(breaker)
				return whiler(cond, body)
			else
				return breaker()
			end
		end)
	end

	local i = 0;
	whiler(
		function() return i < 10 end
		, 
		function(breaker)
			print(i);
			i = i + 1;
			if i % 3 == 0 then
				breaker();
			end
		end);

]]